/**
 * @class tuan.controller.DonHangController
 * @extends extendsClass
 * Description
 */
 Ext.define('tuan.controller.DonHangController', {
    extend: 'Ext.app.Controller',
    refs : [
    {ref : 'donhang_grid',selector : "don-hang-grid-view-master"},
    {ref : 'wapper',selector : 'donhang_wrapper_panel'},
    {ref : 'product_grid', selector : 'products_widget_list_view'},
    {ref : 'choose_xzone',selector :'choose_product_detail_gird'},
    {ref : 'comboboxKH', selector : 'add-new-don-hang-xytpe form combobox[itemId=combobox_KhachHang]'},
    {ref : 'comboboxTT', selector : 'add-new-don-hang-xytpe form #combobox_TinhThanh'},
    {ref : 'formAdd', selector : 'add-new-don-hang-xytpe form'},
    {ref : 'formAddStep2', selector : 'add-new-order-step2 form'},
    {ref : 'addOrderWindow', selector : 'add-new-don-hang-xytpe'},
    {ref : 'addOrderWindowStep2', selector : 'add-new-order-step2'},
    {ref : 'comboboxVanchuyen', selector : 'add-new-order-step2 form #combobox_phuongthucvanchuyen'},
    {ref : 'comboboxThanhtoan', selector : 'add-new-order-step2 form #combobox_phuongthucthanhtoan'},
    {ref : 'pagingOrderMaster', selector : '#paging_grid_order_master'},
    {ref : 'formOrderDetail', selector : 'donhang_wrapper_panel form[itemId=formOrderDetail]'},
    {ref : 'girdOrderDetail',selector : 'donhang_wrapper_panel grid[itemId=orderDetail_viewGird]'},
    {ref : 'thongke', selector : 'tab-thong-ke-donhang'}
    ],
    loaded : false,
    loadedThongKeTinhHinhDoanhThu : false,
    loadedThongKeSanPham : false,
    views : ['donhang.DonHangGridView','donhang.AddNewDonHangWindow','sanpham.ProductDataView',
    'donhang.ChooseProduct','donhang.AddNewDonHangWindowStep2','donhang.DonHangWapperView','donhang.ThongKeView'],
    stores : ['CategoriesStore','ProductStore','TinhThanhStore','HinhThucThanhToanStore',
    'HinhThucVanChuyenStore','OrderStore','OrderDetailStore','StatusOrderStore','CustomerStore',
    'OrderDetailStore','SanphamStore','ThongKeTheoNgayThangStore','ThongKeSanPhamTopStore','CustomerStore'],
    init : function(){
        this.control({
            '#submitThongKeSanPhamTop' : {
                click : this.sumitThongKeSanPhamTop,
            },
            'don-hang-grid-view-master #btnLocDonHangDangXyLy' : {
                click : this.locDonHangDangXyLy
            },
            'tab-thong-ke-donhang button[itemId=submit_form_thongketheongaythang]' : {
                click : this.submitThongKeTheoNgayThang
            },
            '#reload_form_thongketheongaythang' : {
                click : this.reloadThongKeTheoNgayThang
            },
            'tab-thong-ke-donhang' : {
                tabchange : function(tabPanel,newTab,oldTab,eOpts){
                    // console.log((tabPanel.getActiveTab()).title )
                    // console.log(tabPanel.getActiveTab())
                    itemId = (tabPanel.getActiveTab()).itemId;
                    console.log(itemId)
                    if(itemId === 'thong_ke_san_pham_DonHang_id'){
                        tabThongkesanpham = Ext.ComponentQuery.query('#thongkeview_id > #thong_ke_san_pham_DonHang_id > #wapper_thongkesanpham_id')[0];
                        panelThongkesanpham = Ext.ComponentQuery.query('#thongkeview_id > #thong_ke_san_pham_DonHang_id > #panel_thongkesanpham')[0];
                        console.log(tabThongkesanpham);
                        if(this.loadedThongKeSanPham===false){
                            store = Ext.getStore('ThongKeSanPhamTopStore');
                            var d = new Date();
                            var m= d.getMonth();
                            var y = d.getFullYear();
                            store.getProxy().extraParams = '';
                            store.getProxy().extraParams = {thang : (m+1),nam : y};
                            store.load();
                            tabThongkesanpham.add({xtype : 'thongkesanphamtop_xtype',store : store});

                            panelThongkesanpham.update('<h2>Top danh sách sản phẩm được mua nhiều nhất tháng '+(m+1)+'/'+y+' </h2>');
                            this.loadedThongKeSanPham = true
                        }
                    }
                }
            },
            'donhang_wrapper_panel' : {                           
              tabchange: function(tabPanel, newTab, oldTab, eOpts)  {

                if(this.loadedThongKeTinhHinhDoanhThu===false){
                    tabtinhhinhdoanhthu = Ext.getCmp('tab_tinh_hinh_doanh_thu');
                    // tabtinhhinhdoanhthu.add({xtype : ''});
                    // console.log(tabtinhhinhdoanhthu);
                    store = Ext.getStore('ThongKeTheoNgayThangStore');
                    var d = new Date();
                    var m= d.getMonth();
                    var y = d.getFullYear();
                    store.getProxy().extraParams = {thang : (m+1),nam : y};
                    store.load();

                    total = 0;


                    setTimeout(function(){
                        store.on("load", function (st) {
                            t = '',
                            n = '',
                            st.each(function(record){
                                total += record.get('thanhtien');
                                t = record.get('thang');
                                n = record.get('nam');
                            })

                            panelInfo = Ext.getCmp('thongke_xtemplate_ngaythang');
                            panelInfo.update('<h4>THỐNG KÊ SỨC MUA HÀNG THEO NGÀY TRONG THÁNG '+(t)+'/'+n+'</h4>'
                                +'<br/> Tổng số tiền : '+ Ext.util.Format.currency(total, 'VND ')
                            );
                            total = 0;
                            
                        });
                    },1000)

                    tabtinhhinhdoanhthu.add({xtype : 'thongketheothang_xtype',store : store});
                    
                    this.loadedThongKeTinhHinhDoanhThu = true
                }

              }
            },
            'donhang_wrapper_panel button[itemId=btn_add_new_order]' : {
                click : function(){
                    window_add_new_order = Ext.create('tuan.view.donhang.AddNewDonHangWindow');
                    window_add_new_order.show();
                    Ext.getCmp("choose_product_oredr").add({xtype : "products_widget_list_view"});
                }
            },
            'products_widget_list_view' : {
                beforerender : this.loadProductGrid,
                selectionchange : this.selectChangeProduct
            },
            "choose_product_detail_gird" : {
                edit : function(src,e){
                    var record = e.record;
                    // console.log("edit: " + record.get("quantity"));
                    // console.log(this.getChoose_xzone().getStore());
                    itemProductStores = this.getChoose_xzone().getStore();
                    itemProductStores.each(function(item) {
                     console.log(item.get("quantity"));
                 });
                }
            },
            "add-new-don-hang-xytpe form" : {
                beforerender : this.loadCombox
            },
            "add-new-order-step2 form" : {
                beforerender : this.loadCombox2
            },
            "add-new-don-hang-xytpe form #combobox_KhachHang" : {
                select : function(src,record){
                    model = record[0].data;
                    form = this.getFormAdd().getForm();
                    form.findField("customer_name").setValue(model.fullname);
                    form.findField("customer_phone").setValue(model.phone);
                    form.findField("ten_nguoi_nhan").setValue(model.fullname);
                    form.findField("so_phone_nguoi_nhan").setValue(model.phone);
                    form.findField("address").setValue(model.address);
                    form.findField("billing_address").setValue(model.billing_address);
                }
            },
            "#process_order" : {
                click : this.submitForm
            },
            '#process_order_save' : {
                click : this.submitFormStep2
            },
            'don-hang-grid-view-master' : {
                beforerender : this.loadListOrder,
                itemclick : this.getOrderDetail
            },
            '#paging_grid_order_master' : {
                beforerender : this.loadPaging
            },
            'donhang_wrapper_panel combobox[itemId=filterComboboxDonHang]': {
                select : this.selectFilterStatusOrder
            },
            "donhang_wrapper_panel button[itemId=filterDonhangtrongngay]" : {
                click : this.loadDonHangTrongNgay
            },
            '#btnRefreshOrder' : {
                click : this.refreshOrder
            },
            'don-hang-grid-view-master combobox[itemId=filterKhachHangCombobox]' : {
                beforerender : this.loadComboxFilterCustomer,
                select : this.selectFilterCustomerOrder
            },
            'button[itemId=btnUpdateOrder]' : {
            // '#btnUpdateOrder' : {
                click : this.updateOrder
            
            }
            
        })
},
updateOrder : function(src){
    form = src.up('form');
    dataForm = form.getForm().getValues();

    // console.log(dataForm.getValues());
    if(form.isValid()){
        order  = Ext.getStore('OrderStore');
        order.each(function(o){
            id = o.get('id');
            billing_address = dataForm.billing_address;
            address = dataForm.address;
            note = dataForm.note;
            customer_phone = dataForm.customer_phone;
            
            if(id === dataForm.id){
                console.log('node');
                o.set('note' , 'test thoi');
                o.getChanges();
                order.save();
            }
        })
    }
},
sumitThongKeSanPhamTop : function(src){
    // console.log('click');
    form = src.up('form');
    if(form.isValid()){

        data = form.getForm();
        thang  = data.findField('thang').getValue();
        nam  = data.findField('nam').getValue();

        store = Ext.getStore('ThongKeSanPhamTopStore');

        store.getProxy().extraParams = '',
        store.getProxy().extraParams = {thang : thang,nam : nam};
        store.load();

        panelThongkesanpham = Ext.ComponentQuery.query('#thongkeview_id > #thong_ke_san_pham_DonHang_id > #panel_thongkesanpham')[0];
        panelThongkesanpham.update('<h2>Top danh sách sản phẩm được mua nhiều nhất tháng '+thang+'/'+nam+' </h2>');
    };
},
locDonHangDangXyLy : function(){
    grid = this.getDonhang_grid();
    gridStore = grid.getStore();
    gridStore.clearFilter();
    gridStore.getProxy().extraParams = '';
    gridStore.getProxy().extraParams = {filter : '[{"property" : "status","value" :"'+1+'","type" : "numeric","comparison" : "khac"}]'};
    setTimeout(function(){
        gridStore.load();

    },1000);
},
reloadThongKeTheoNgayThang : function(){
    // console.log(tabtinhhinhdoanhthu);
    store = Ext.getStore('ThongKeTheoNgayThangStore');
    var d = new Date();
    var m= d.getMonth();
    var y = d.getFullYear();
    store.getProxy().extraParams = {thang : (m+1),nam : y};
    store.load();

    total = 0;

    store.on("load", function (st) {
        st.each(function(record){
            total += record.get('thanhtien');
            
        })

        panelInfo = Ext.getCmp('thongke_xtemplate_ngaythang');
        panelInfo.update('<h4>THỐNG KÊ SỨC MUA HÀNG THEO NGÀY TRONG THÁNG '+(m+1)+'/'+y+'</h4>'
            +'<br/> Tổng số tiền : '+ Ext.util.Format.currency(total, 'VND ')
        );
        total = 0;
    });
},
submitThongKeTheoNgayThang : function(src){
    console.log('click');
    form = src.up('form');
    if(form.isValid()){

        data = form.getForm();
        thang  = data.findField('thang').getValue();
        nam  = data.findField('nam').getValue();

        store = Ext.getStore('ThongKeTheoNgayThangStore');

        store.getProxy().extraParams = '',
        store.getProxy().extraParams = {thang : thang,nam : nam};
        store.load();

        panelInfo = Ext.getCmp('thongke_xtemplate_ngaythang');
        panelInfo.update('<h4>THỐNG KÊ SỨC MUA HÀNG THEO NGÀY TRONG THÁNG '+thang+'/'+nam+'</h4>'
            +'<br/> Tổng tiền : '+ Ext.util.Format.currency(total, 'VND ')
        );
    }
},
getOrderDetail : function (src,record){
    id = record.getId();
    // Ext.getCmp('actionId_account').setValue(id);
    
    ngaygh = new Date(record.get('ngay_giao_hang'));
    ngaydh = new Date(record.get('order_date'));
    ngaydl = new Date(record.get('deadline'));
    console.log(ngaygh);
    this.getFormOrderDetail().loadRecord(record);
    this.getFormOrderDetail().getForm().findField('ngay_giao_hang').setValue(ngaygh);
    this.getFormOrderDetail().getForm().findField('order_date').setValue(ngaydh);
    this.getFormOrderDetail().getForm().findField('deadline').setValue(ngaydl);

    //Lay OrderDetail
    orderDetailStore = Ext.getStore('OrderDetailStore');
    orderDetailStore.getProxy().extraParams =  {filter : '[{"property" : "order_id","value" :"'+id+'","type" : "string","comparison" : "eq"}]'};
    

    orderDetailGrid = this.getGirdOrderDetail();

    setTimeout(function(){
        orderDetailStore.load();
        orderDetailGrid.reconfigure(orderDetailStore);
        orderDetailGrid.headerCt.down('gridcolumn[dataIndex=price]').renderer = function (value, meta,record) {
            // meta.style = 'color: #f00';
            quantity = record.get('quantity');
            // console.log(quantity);
            v = quantity*value;
            return quantity +'x'+ Ext.util.Format.currency(value, 'VND ');
            // return value;
        };
        total = Ext.ComponentQuery.query('#total_text')[0];
        total.update('Tổng tiền : '+ Ext.util.Format.currency(record.get('total'),' VND'));
    },1000);

},
selectFilterCustomerOrder : function(src,records){
    id = records[0].get('id');
    grid = this.getDonhang_grid();
    gridStore = grid.getStore();
    gridStore.clearFilter();
    gridStore.getProxy().extraParams = '';
    gridStore.getProxy().extraParams = {filter : '[{"property" : "account_id","value" :"'+id+'","type" : "string","comparison" : "eq"}]'};
    setTimeout(function(){
        gridStore.load();
    },1000);
},
loadComboxFilterCustomer : function(){
    store = Ext.getStore('CustomerStore');
    combobox = Ext.ComponentQuery.query('#filterKhachHangCombobox')[0];
    store.load();
    combobox.bindStore(store);
},
refreshOrder : function(){
    grid = this.getDonhang_grid();
    gridStore = grid.getStore();
    gridStore.clearFilter();
    gridStore.getProxy().extraParams = '';
    gridStore.clearFilter();
    gridStore.load();
},
loadDonHangTrongNgay : function(){
    curdate = new Date();
    stringdate =(curdate.getUTCMonth()+1)+'/'+curdate.getUTCDate()+'/'+curdate.getUTCFullYear();
    valuetime = new Date(stringdate).getTime();

    grid = this.getDonhang_grid();
    gridStore = grid.getStore();
    gridStore.clearFilter();
    gridStore.getProxy().extraParams = {filter : '[{"property" : "order_date","value" :"'+stringdate+'","type" : "date","comparison" : "eq"}]'};

    setTimeout(function(){
            gridStore.load();
    },1000);

},
selectFilterStatusOrder : function(src,records){
    id = records[0].get('id');
    grid = this.getDonhang_grid();
    gridStore = grid.getStore();
    gridStore.clearFilter();
    gridStore.getProxy().extraParams = '';
    gridStore.getProxy().extraParams = {filter : '[{"property" : "status","value" :"'+id+'","type" : "string","comparison" : "eq"}]'};
    setTimeout(function(){
        gridStore.load();

    },1000);


    Ext.Ajax.on("requestcomplete", function(conn, response, options){
        //         grid.reconfigure(null);
        // grid.reconfigure(gridStore);
        paging = Ext.getCmp('paging_grid_order_master');
        paging.bindStore(gridStore);
            data = Ext.JSON.decode(response.responseText);
            if(data.lists === ''){
                Ext.Msg.alert('Empty','Không tìm thấy');
            }
    });

},
loadPaging : function(){
    // paging = Ext.getCmp('paging_grid_order_master');
    // orderStore = Ext.getStore("OrderStore");
    // orderStore.load();
    // orderStore.on("load", function (orders) {
    //     paging.bindStore(orders);
    // });
},
loadListOrder : function(){
    Ext.Ajax.on("beforerequest", function(){
        Ext.getBody().mask("Loading...", 'loading');
    });
    Ext.Ajax.on("requestcomplete", function(){
        window.parent.Ext.getBody().unmask();
    });
    grid = this.getDonhang_grid();
    paging = Ext.getCmp('paging_grid_order_master');
    orderStore = Ext.getStore("OrderStore");
    orderStore.load();


    //render Grid
    statusOrder = Ext.getStore('StatusOrderStore');
    statusOrder.load();

    statusOrder.on('load',function(statusStore){
        grid.headerCt.down('gridcolumn[dataIndex=status]').renderer = function (value, meta,record) {
            // meta.style = 'color: #f00';
            statusrecord = statusStore.findRecord('id',value);
            // console.log('1');
            return statusrecord.get('name');
        };
         window.parent.Ext.getBody().unmask();
        // grid.reconfigure(orderStore);
        orderStore.on("load", function (store) {
            grid.reconfigure(store);
        });
    });
    grid.headerCt.down('gridcolumn[dataIndex=order_date]').renderer = function (value, meta,record) {
            // meta.style = 'color: #f00';
            curdate = new Date();
            newdata = new Date(value);

            stringdate =curdate.getUTCDate()+'/'+curdate.getUTCMonth()+'/'+curdate.getUTCFullYear();
            orderdate =newdata.getUTCDate()+'/'+newdata.getUTCMonth()+'/'+newdata.getUTCFullYear();
            orderdateR =newdata.getUTCDate()+'/'+(newdata.getUTCMonth()+1)+'/'+newdata.getUTCFullYear();
            if(stringdate === orderdate){
                meta.style = 'color: #088A29';
            }
            return orderdateR;
    };
    paging.bindStore(orderStore);

},
submitFormStep2 : function(){
    form = this.getFormAddStep2();
    addOrder = this.getAddOrderWindowStep2();
    dataGetForm = form.getForm();
    status = dataGetForm.findField('status').getValue();

    if(form.isValid()){
        formOrder = JSON.parse(sessionStorage.getItem('dataFromStep1'));
        delineOrder = new Date (formOrder.deadline);
        ngaygiaohangOrder = new Date (formOrder.ngay_giao_hang);
        orderDetails = formOrder.orderDetail;
        hinh_thuc_thanh_toan = dataGetForm.findField('hinh_thuc_thanh_toan').getValue();
        hinh_thuc_van_chuyen = dataGetForm.findField('hinh_thuc_van_chuyen').getValue();
        status = dataGetForm.findField('status').getValue();
        manguoilap =  sessionStorage.getItem('username');
        tennguoilap =  sessionStorage.getItem('fullname');

        orderStore = Ext.getStore('OrderStore');


        orderStore.add({account_id : formOrder.account_id,customer_name : formOrder.customer_name,
            customer_phone : formOrder.customer_phone, billing_address : formOrder.billing_address,
            address : formOrder.address, order_date : new Date(),note : formOrder.note,
            status : status, deadline : delineOrder, ngay_giao_hang : ngaygiaohangOrder,
            hinh_thuc_thanh_toan : hinh_thuc_thanh_toan, hinh_thuc_van_chuyen : hinh_thuc_van_chuyen,
            tinhid : formOrder.tinhid, total : formOrder.total, ten_nguoi_lap_hoa_don : tennguoilap,
            ma_nguoi_nhap : manguoilap, ten_nguoi_nhan : formOrder.ten_nguoi_nhan, so_phone_nguoi_nhan : formOrder.so_phone_nguoi_nhan
        });
            // pxy = orderStore.getProxy();
            // pxy.setExtraParam('Deleted', false);
            orderStore.sync({
                success: function(batch, options) {
                    orderid = batch.proxy.getReader().jsonData.id;
                    orderDetailStore = Ext.getStore('OrderDetailStore');
                    for (var key in orderDetails) {
                        orderDetailStore.add({order_id : orderid,product_id : orderDetails[key].id,quantity : orderDetails[key].quantity });
                    }
                    orderDetailStore.sync();
                    sessionStorage.removeItem('dataFromStep1');
                    Ext.Msg.alert('Success!', 'Bạn đã thêm đơn hàng thành công.');
                    
                    addOrder.close();
                },
                failure: function(batch) {
                    // Ext.Msg.alert("Failed", batch.operations[0].request.scope.reader.jsonData["message"]);
                }
            });
        }
        
        // Ext.Ajax.on("requestcomplete", function(conn, response, options){
        //     data = Ext.JSON.decode(response.responseText);

        // });
},
submitForm : function(){        
    form = this.getFormAdd();
    dataGetForm = form.getForm();
    dataForm = {};
    account_id = dataGetForm.findField('account_id').getValue();
    customer_name = dataGetForm.findField('customer_name').getValue();
    customer_phone = dataGetForm.findField('customer_phone').getValue();
    tennguoinhan = dataGetForm.findField('ten_nguoi_nhan').getValue();
    sophonenguoinhan = dataGetForm.findField('so_phone_nguoi_nhan').getValue();
    address = dataGetForm.findField('address').getValue();
    billing_address = dataGetForm.findField('billing_address').getValue();
    tinhid = dataGetForm.findField('tinhid').getValue();
    note = dataGetForm.findField('note').getValue();
    ngay_giao_hang = dataGetForm.findField('ngay_giao_hang').getValue();
    deadline = dataGetForm.findField('deadline').getValue();


    dataForm['account_id'] = account_id;
    dataForm['customer_name'] = customer_name;
    dataForm['customer_phone'] = customer_phone;
    dataForm['address'] = address;
    dataForm['billing_address'] = billing_address;
    dataForm['ten_nguoi_nhan'] = tennguoinhan;
    dataForm['so_phone_nguoi_nhan'] = sophonenguoinhan;
    dataForm['tinhid'] = tinhid;
    dataForm['note'] = note;
    dataForm['ngay_giao_hang'] = ngay_giao_hang.getTime();
    dataForm['deadline'] = deadline.getTime();

    addOrder = this.getAddOrderWindow();

    productStore = this.getChoose_xzone().getStore();
    orderDetails = {};
    totalOrder = 0.0;
    productStore.each(function(p,index) {
        totalOrder += p.get('quantity') * p.get('price');
        tmp = {};
        tmp['id'] = p.get('id');
        tmp['quantity'] = p.get('quantity');
        orderDetails[index] = tmp;
    });

    dataForm['orderDetail'] = orderDetails;
    dataForm['total'] = totalOrder;

    console.log(productStore);
    if(form.isValid()){
        console.log(deadline.getTime());
        if(productStore.data.items.length  !== 0){
            sessionStorage.setItem('dataFromStep1',JSON.stringify(dataForm));
            window_add_new_orderStep2 = Ext.create('tuan.view.donhang.AddNewDonHangWindowStep2');
            window_add_new_orderStep2.show();
            addOrder.close();

        }else{
            Ext.Msg.alert('Error','Vui long chon san pham!')
        }
    }
},
loadCombox : function(){
    storeKH = Ext.getStore('CustomerStore');
    storeTT = Ext.getStore('TinhThanhStore');
    combobox = this.getComboboxKH();
    comboboxTT  = this.getComboboxTT();
    combobox.bindStore(storeKH);
    comboboxTT.bindStore(storeTT);
},
loadCombox2 : function(){
 storeThanhToan = Ext.getStore('HinhThucThanhToanStore');
 comboboxThanhToan = this.getComboboxThanhtoan();
 comboboxThanhToan.bindStore(storeThanhToan);
 storeVanChuyen = Ext.getStore('HinhThucVanChuyenStore');
 comboboxVanChuyen = this.getComboboxVanchuyen();
 comboboxVanChuyen.bindStore(storeVanChuyen);

  comboxFilterStatus = Ext.ComponentQuery.query('#filterStatusOrderStep2')[0];
  storeStatus = Ext.getStore('StatusOrderStore');
  storeStatus.load();
  comboxFilterStatus.bindStore(storeStatus);

},
selectChangeProduct : function(view, nodes){
    var l = nodes.length;
    temp = [];
    for (var i = nodes.length - 1; i >= 0; i--) {
        t = {},
        t['id'] =  nodes[i].data.id;
        t['product_name'] = nodes[i].data.product_name;
        t['price'] = nodes[i].data.price;
        t['weight'] = nodes[i].data.weight;
        t['cate_id'] = nodes[i].data.cate_id;
        t['quantity'] = 1;
        temp[i] = t;
    };
    Ext.define("chooseproduct", {
        extend : "Ext.data.Model",
        fields : ["product_name","price","weight","cate_id","quantity"]
    });
    var ps = Ext.create('Ext.data.Store',{
        model : 'chooseproduct',
        data : temp
    })
    this.getChoose_xzone().reconfigure(ps);
},
loadProductGrid : function(){
    // orderStore = Ext.getStore('OrderStore');
    // orderStore.add({account_id : 5});
    // orderStore.sync();

    Ext.Ajax.on("beforerequest", function(){
        Ext.getBody().mask("Loading...", 'loading');
    });
    Ext.Ajax.on("requestcomplete", function(){
        window.parent.Ext.getBody().unmask();
    });
    Ext.Ajax.on("requestexception", function(){
        Ext.Msg.alert('Error','Sorry something wrong!');
        window.parent.Ext.getBody().unmask();
    });
    storeProduct = Ext.getStore("ProductStore"); 

    p = this.getProduct_grid();

    storeCates = Ext.getStore('CategoriesStore').load();
    storeCates.on('load',function(cates){
        localCate = {};
        storeCates.each(function(cate,index) {
            tmp = {};
            tmp['id'] = cate.get('id');
            tmp['catename'] = cate.get('cate_name');

            localCate[index] = tmp;
        });
        localStorage.setItem('localStoreCates', JSON.stringify(localCate));
        storeProduct.load();
        storeProduct.on("load",function(record){
            p.reconfigure(storeProduct);
        });
    });
},
actionIndex : function(){
 if(this.loaded === false){
  // Ext.ComponentQuery.query('#don_hang_view_zone #don_hang_gird')[0].add({xtype : "don-hang-grid-view-master"});
  comboxFilterStatus = Ext.ComponentQuery.query('#filterComboboxDonHang')[0];
  storeStatus = Ext.getStore('StatusOrderStore');
  storeStatus.load();
  comboxFilterStatus.bindStore(storeStatus);
  this.loaded = true;
}
}

});